/**
 * @author https://vue-admin-beautiful.com （不想保留author可删除）
 * @description 路由拦截状态管理，目前两种模式：all模式与intelligence模式，其中partialRoutes是菜单暂未使用
 */
import { asyncRoutes, constantRoutes } from '@/router'
import { UserMenus } from '@/api/user'
import store from '@/store'
import { convertRouter, filterAsyncRoutes } from '@/utils/handleRoutes'

const state = () => ({
  routes: [],
  partialRoutes: [],
})
const getters = {
  routes: (state) => state.routes,
  partialRoutes: (state) => state.partialRoutes,
}
const mutations = {
  setRoutes(state, routes) {
    state.routes = constantRoutes.concat(routes)
  },
  setAllRoutes(state, routes) {
    state.routes = routes.concat(constantRoutes)
  },
  setPartialRoutes(state, routes) {
    state.partialRoutes = constantRoutes.concat(routes)
  },
}
const actions = {
  async setRoutes({ commit }, permissions) {
    //(filterAsyncRoutes)根据用户权限过滤路由配置
    const finallyAsyncRoutes = await filterAsyncRoutes([...asyncRoutes], permissions)
    commit('setRoutes', finallyAsyncRoutes)
    return finallyAsyncRoutes
  },

  async setAllRoutes({ commit, state }) {
    //调用getRouterList()方法来获取路由列表的数据

    let box = {
      uCode: store.getters['user/uCode'],
    }
    let { data } = await UserMenus(box)
    data.push({ path: '*', redirect: '/404', hidden: true })
    data.push({
      path: '/',
      component: 'Layout',
      redirect: 'index',
      children: [
        {
          path: 'index',
          name: 'Index',
          component: '@views/index/index',
          meta: {
            title: '首页',
            icon: 'home',
            affix: true,
          },
        },
      ],
    })

    let accessRoutes = await convertRouter(data)
    commit('setAllRoutes', accessRoutes)
    return state.routes
  },
  setPartialRoutes({ commit }, accessRoutes) {
    commit('setPartialRoutes', accessRoutes)
    return accessRoutes
  },
}
export default { state, getters, mutations, actions }
